<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

      <!-- 下拉框+模糊搜索 -->
      <el-row>
        <el-col :span="4">
          <el-form-item label="合同编号" prop="projectCode">
            <el-select v-model="queryParams.projectCode" filterable placeholder="请输入或选择合同编号" style="width: 200px;">
              <el-option
                  v-for="item in projectOptions"
                  :key="item"
                  :label="item"
                  :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="项目名" prop="projectName">
            <el-input
                v-model="queryParams.projectName"
                placeholder="请输入项目名"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>

        <!--<el-form-item label="所属地区" prop="areaId">
          <el-select v-model="queryParams.areaId" placeholder="请选择所属地区" clearable style="width: 180px;">
            <el-option
                v-for="dict in area_id"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>-->
      </el-row>

      <el-row>
        <el-col :span="4">
          <el-form-item label="创建人" prop="createBy">
            <el-input
                v-model="queryParams.createBy"
                placeholder="请输入创建人"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="创建时间">
            <el-date-picker
                v-model="daterangeCreateTime"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="更新人" prop="updateBy">
            <el-input
                v-model="queryParams.updateBy"
                placeholder="请输入更新人"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="更新时间">
            <el-date-picker
                v-model="daterangeUpdateTime"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:projectInfo:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:projectInfo:edit']"
        >修改</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:projectInfo:remove']"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            :disabled="single"
            @click="handleExport"
            v-hasPermi="['system:projectInfo:export']"
        >盈亏</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleSummaryOpen"
            v-hasPermi="['system:projectInfo:summary']"
        >汇总</el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>

    </el-row>

    <el-table v-loading="loading" :data="projectInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" prop="id" v-if="false" />
      <el-table-column label="所属地区" align="center" prop="areaId" v-if="false">
        <template #default="scope">
          <dict-tag :options="area_id" :value="scope.row.areaId"/>
        </template>
      </el-table-column>
      <el-table-column label="合同编号" align="center" prop="projectCode" sortable/>
      <el-table-column label="项目名称" align="center" prop="projectName" sortable :sort-method="nameSort"/>
      <el-table-column label="合同总价款" align="center" prop="totalContract" sortable/>
      <el-table-column label="考核利润率" align="center" prop="assessRate" sortable>
        <template #default="scope">
          <span>{{ scope.row.assessRate * 100 }}%</span>
        </template>
      </el-table-column>
      <el-table-column label="合计采购成本" align="center" prop="procurementCost"  v-if="false"/>
      <el-table-column label="其他间接费用" align="center" prop="indirectCost"  v-if="false"/>
      <el-table-column label="合计税额" align="center" prop="totalTax"  v-if="false"/>
      <el-table-column label="开累除税成本" align="center" prop="cost" sortable/>
      <el-table-column label="开累除税产值" align="center" prop="output" sortable/>
      <el-table-column label="利润" align="center" prop="profit" sortable/>
      <el-table-column label="备注" align="center" prop="remark" />

      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" sortable/>
      <!--<el-table-column label="更新人" align="center" prop="updateBy" />-->
      <!--<el-table-column label="更新时间" align="center" prop="updateTime" width="180" >-->
      <!--  <template #header>-->
      <!--<el-table-column label="更新时间" align="center" prop="updateTime" sortable/>-->
      <!--    <span class="sortable-header" @click="handleSort('update_time')" style="position: relative;">-->
      <!--      更新时间-->
      <!--      &lt;!&ndash;<el-icon v-show="sortKey === 'update_time' && sortOrder === 'asc'" class="arrow-icon" style="position: absolute; left: 100%; top: 50%; transform: translateY(-50%);"><ArrowUpBold /></el-icon>&ndash;&gt;-->
      <!--      &lt;!&ndash;<el-icon v-show="sortKey === 'update_time' && sortOrder === 'desc'" class="arrow-icon" style="position: absolute; left: 100%; top: 50%; transform: translateY(-50%);"><ArrowDownBold /></el-icon>&ndash;&gt;-->
      <!--    </span>-->

      <!--  </template>-->
      <!--</el-table-column>-->



      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:projectInfo:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:projectInfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改项目对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="projectInfoRef" :model="form" :rules="rules" label-width="80px">
        <!--<el-form-item label="所属地区" prop="areaId" label-width="140px">
          <el-select v-model="form.areaId" placeholder="请选择所属地区">
            <el-option
                v-for="dict in area_id"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item label="项目名称" prop="projectName" label-width="140px">
          <el-select v-model="form.projectName" filterable placeholder="请输入或选择项目名称" style="width: 200px;" @change="handleProjectNameChange">
            <el-option
                v-for="item in contractOptions"
                :key="item"
                :label="item"
                :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="合同编号" prop="projectCode" label-width="140px">
          <el-select v-model="form.projectCode" filterable placeholder="请输入或选择合同编号" style="width: 200px;" @change="handleProjectCodeChange">
            <el-option
                v-for="item in projectOptions"
                :key="item"
                :label="item"
                :value="item"
            />
          </el-select>
        </el-form-item>
        <!--<el-form-item label="项目名称" prop="projectName" label-width="140px">-->
        <!--  <el-input v-model="form.projectName" placeholder="请输入项目名" style="width: 340px;" />-->
        <!--</el-form-item>-->
        <!--<el-form-item label="合同总价款" prop="totalContract" label-width="140px">-->
        <!--  <el-input v-model="form.totalContract" placeholder="请输入合同总价款" style="width: 340px;" />-->
        <!--</el-form-item>-->
        <el-form-item label="考核利润率" prop="assessRate" label-width="140px">
          <el-input v-model="form.assessRate" placeholder="请输入内部考核利润率" style="width: 170px;" />
        </el-form-item>
        <el-form-item label="备注" prop="remark" label-width="140px">
          <el-input v-model="form.remark" placeholder="请输入备注" style="width: 340px;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <el-dialog :title="summary.title" v-model="summary.open" width="400px" append-to-body>
      <div class="el-summary__tip text-center">

        <div class="centered">
          <el-form-item label="期数选择" prop="dateRange">
            <el-date-picker
                type="monthrange"
                v-model="summary.dateRange"
                format="YYYY-MM"
                value-format="YYYY-MM"
                range-separator="-"
                :style="{ width: '100%' }"
                start-placeholder="开始"
                end-placeholder="结束"
                clearable
                style="width: 200px;">
            </el-date-picker>
          </el-form-item>
        </div>
        <span>请选择一个期数范围。</span>
      </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSummary">确 定</el-button>
        <el-button @click="summary.open = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>



</template>

<script setup name="ProjectInfo">
import { listProjectInfo, getProjectInfo, delProjectInfo, addProjectInfo, updateProjectInfo } from "@/api/system/projectInfo";

const summary = reactive({
  // 是否显示弹出层（明细导入）
  open: false,
  // 弹出层标题（明细导入）
  title: "",
  // 期数范围
  dateRange : []
});

const nameSort = (a, b) => {
  return a.projectName.localeCompare(b.projectName,'zh');
};

const { proxy } = getCurrentInstance();
const { area_id } = proxy.useDict('area_id');

let selectedRow = null; // 添加 selectedRow 变量
const projectOptions = ref([]);
const contractOptions = ref([]);
const projectInfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreateTime = ref([]);
const daterangeUpdateTime = ref([]);
const nowDate = ref(null);
// 获取当前日期
const currentDate = new Date();
const currentYear = currentDate.getFullYear();
const currentMonth = currentDate.getMonth() + 1;
nowDate.value = `${currentYear}年${currentMonth}月`;
let sortKey = '';
let sortOrder = '';

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    areaId: null,
    projectCode: null,
    projectName: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    totalContract: null,
    assessRate: null,
    sortKey: '',
    sortOrder: ''

  },
  rules: {
    projectCode: [
      { required: true, message: "合同编号不能为空", trigger: "blur" }
    ],
    projectName: [
      { required: true, message: "项目名不能为空", trigger: "blur" }
    ],
    /*totalContract: [
      { required: true, message: "合同总价款不能为空", trigger: "blur" }
    ],*/
    /*areaId: [
      { required: true, message: "请选择所属地区", trigger: "blur" }
    ],*/
  },
  projectInfo: {
    id: null,
    projectCode: null,
    projectName: null,
  }
});

const { queryParams, form, rules } = toRefs(data);

// 获取当前 URL 中的查询参数部分
const queryString = window.location.search;
// 使用 URLSearchParams 对象解析查询参数
const urlParams = new URLSearchParams(queryString);
// 获取特定参数的值
queryParams.value.areaId = urlParams.get('areaId');
console.log("areaId: " + queryParams.value.areaId);

/** 汇总按钮操作 */
function handleSummaryOpen() {
  summary.title = "项目汇总";
  summary.open = true;
};

/** 查询项目列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {
  };
  queryParams.value.sortKey = sortKey;
  queryParams.value.sortOrder = sortOrder;
  // console.log('sortKey: ' + sortKey)
  // console.log('sortOrder: ' + sortOrder)
  queryParams.value.params["areaId"] = queryParams.value.areaId;
  if (null != daterangeCreateTime && '' !== daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  if (null != daterangeUpdateTime && '' !== daterangeUpdateTime) {
    queryParams.value.params["beginUpdateTime"] = daterangeUpdateTime.value[0];
    queryParams.value.params["endUpdateTime"] = daterangeUpdateTime.value[1];
  }
  listProjectInfo(queryParams.value).then(response => {
    projectInfoList.value = response.dataList.rows;
    projectOptions.value = response.projectCodeList;
    contractOptions.value = response.contractNameList;
    total.value = response.dataList.total;
    loading.value = false;
  });
}

/** 点击表头排序 */
function handleSort(key) {
  if (sortKey === key) {
    // 如果点击的字段与当前的 sortKey 相同，则切换排序方式
    sortOrder = sortOrder === 'asc' ? 'desc' : 'asc';
  } else {
    // 如果点击的字段与当前的 sortKey 不同，则将点击的字段设置为新的 sortKey，并默认升序排序
    sortKey = key;
    sortOrder = 'desc';
  }

  getList(); // 调用查询方法进行排序
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    areaId: null,
    indirectCost: null,
    output: null,
    procurementCost: null,
    profit: null,
    projectCode: null,
    projectName: null,
    remark: null,
    totalTax: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    totalContract: null,
    assessRate: null
  };
  proxy.resetForm("projectInfoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = [];
  daterangeUpdateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

function handleProjectCodeChange(value) {
  // 找到选中合同编号对应的项目名称
  const index = projectOptions.value.findIndex(item => item === value);
  if (index !== -1 && index < contractOptions.value.length) {
    // 设置项目名称为对应索引的项目名称
    form.value.projectName = contractOptions.value[index];
  } else {
    form.value.projectName = ''; // 如果找不到对应的项目名称，则清空项目名称
  }
}
function handleProjectNameChange(value) {
  // 找到选中合同编号对应的项目名称
  const index = contractOptions.value.findIndex(item => item === value);
  if (index !== -1 && index < projectOptions.value.length) {
    // 设置项目名称为对应索引的项目名称
    form.value.projectCode = projectOptions.value[index];
  } else {
    form.value.projectCode = ''; // 如果找不到对应的项目名称，则清空项目名称
  }
}

const projectInfo = ref({
  id: null,
  projectCode: null,
  projectName: null,
});

const filename = ref(null); // 添加 filename 变量

// 多选框选中数据
function handleSelectionChange(selection) {
  selectedRow = selection.length ? selection[0] : null; // 更新 selectedRow
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;

  // 如果只有一个项目被选中，更新 projectInfo
  if (selection.length === 1) {
    projectInfo.value = { ...selection[0] };
    filename.value = selection[0].projectName;
  } else {
    // 如果没有项目被选中或多个项目被选中，重置 projectInfo
    projectInfo.value = {
      id: null,
      projectCode: null,
      projectName: null,
    };
    filename.value = null; // 重置 filename
  }
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.areaId = queryParams.value.areaId;
  open.value = true;
  title.value = "添加项目";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getProjectInfo(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改项目";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["projectInfoRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateProjectInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProjectInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除合同编号为"' + _ids + '"的数据项？').then(function() {
    return delProjectInfo(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}



/** 导出按钮操作 */
function handleExport() {
  if (filename.value) { // 确保 filename 不为空
    const extension = '年度盈亏分析表.xlsx'; // 假设导出文件的扩展名是 .xlsx，可以根据实际情况修改
    const fullFilename = `${filename.value}${extension}`;
    proxy.download('system/projectInfo/export', {
      ...projectInfo.value
    }, fullFilename);
  }
}

/** 汇总按钮操作 */
function handleSummary() {
    const start = summary.dateRange[0];
    const end = summary.dateRange[1];
    console.log("开始时间：" + start + "，结束时间：" + end);
    const extension = '建设板块进度、产值、成本汇总表.xlsx'; // 假设导出文件的扩展名是 .xlsx，可以根据实际情况修改
    console.log("日期字符串：" + nowDate.value);
    const fullFilename = `${nowDate.value}${extension}`;
    proxy.download('system/projectInfo/summary?start=' + start + '&end=' + end, {
      ...projectInfo.value
    }, fullFilename);
}

getList();

</script>
